package cn.itcast.web.sevlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet02 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //获取method
            String method = request.getParameter("method");
            //获取当前使用者字节码文件
            Class clazz = this.getClass();
            //反射获取对应方法
            Method declaredMethod = clazz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //暴力
            declaredMethod.setAccessible(true);
            //调用方法
            Object invoke = declaredMethod.invoke(this, request, response);
            //防止返回值是否为null
            if(invoke!=null&&!"".equals(invoke)){
                //判断返回值是否为String类型
                if(invoke instanceof String){
                    String page = (String) invoke;
                    //看是否以转发开头
                    if(page.startsWith("forward:")){
                        request.getRequestDispatcher("/"+page.substring(8)).forward(request,response);
                        //判断是否以重定向开头
                    }else if(page.startsWith("redirect:")){
                        response.sendRedirect(super.getServletContext().getContextPath()+
                                "/"+page.substring(9));
                    }else {//默认转发
                        request.getRequestDispatcher("/"+page).forward(request,response);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
